<?php

namespace App\Http\Controllers\Recharge;

use App\Http\Controllers\Controller;
use App\Models\AgentCashback;
use App\Models\Calls;
use App\Models\Flow;
use App\Models\Order;
use App\Models\OrderPayNotice;
use App\Models\RechargeOrder;
use App\Models\User;
use function date;
use EasyWeChat\Factory;
use Exception;
use function json_decode;
use Request;
use Validator;
use Session;
use DB;
use Omnipay\Omnipay;
use Log;

class CallbackController extends Controller
{

    // 校验失败返回xml
    private static $fail_xml = <<<XML
<xml>
  <return_code><![CDATA[FAIL]]></return_code>
  <return_msg><![CDATA[FAIL]]></return_msg>
</xml>
XML;

    // 校验成功，并更新订单状态成功返回的xml
    private static $success_xml = <<<XML
<xml>
  <return_code><![CDATA[SUCCESS]]></return_code>
  <return_msg><![CDATA[OK]]></return_msg>
</xml>
XML;


    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        Log::info('CallbackController __construct');
    }


    /**
     * 微信支付回调检验并更新订单状态
     */
    public function wxPayCallback()
    {
        Log::info("支付callback校验开始：================================");

        $content = file_get_contents('php://input');

        // 防止恶意请求
        if (empty($content)) {
            header("HTTP/1.1 404 Not Found");
            exit;
        }

        Log::info("content:" . $content);

        $xml     = simplexml_load_string($content);
        $orderId = $xml->out_trade_no;
        \Log::info($orderId);

        $order = Order::where('order_sn', $orderId)->first();
        if (empty($order) || $order->status != 1) {
            Log::info("获取ordersn:{$order}订单信息失败");
            header("HTTP/1.1 404 Not Found");
            exit;
        }

        $app = app("easyWechat");

        $response = $app->handlePaidNotify(function ($message, $fail) {
            $orderId = $message['out_trade_no'];

            $this->savePayNotice((object)$message);

            $order = Order::where('order_sn', $orderId)->first();
            if (empty($order) || $order->status != 1) {
                return true;
            }

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    // 改变充值状态
                    $order->status = 2;
                    $order->success_time = time();
                    $b = $order->save();

                    // 用户支付失败
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->status = 'paid_fail';
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            // 你的逻辑
            return true;
        });

        return $response->send(); // Laravel 里请使用：return $response;
    }

    public function savePayNotice($xml) {
        $pn = new OrderPayNotice;
        $pn->return_code = isset($xml->return_code) ? $xml->return_code : '';
        $pn->return_msg = isset($xml->return_msg) ? $xml->return_msg : '';
        $pn->appid = isset($xml->appid) ? $xml->appid : '';
        $pn->mch_id = isset($xml->mch_id) ? $xml->mch_id : '';
        $pn->device_info = isset($xml->device_info) ? $xml->device_info : '';
        $pn->nonce_str = isset($xml->nonce_str) ? $xml->nonce_str : '';
        $pn->sign = isset($xml->sign) ? $xml->sign : '';
        $pn->sign_type = isset($xml->sign_type) ? $xml->sign_type : '';
        $pn->result_code = isset($xml->result_code) ? $xml->result_code : '';
        $pn->err_code = isset($xml->err_code) ? $xml->err_code : '';
        $pn->err_code_des = isset($xml->err_code_des) ? $xml->err_code_des : '';
        $pn->openid = isset($xml->openid) ? $xml->openid : '';
        $pn->is_subscribe = isset($xml->is_subscribe) ? $xml->is_subscribe : '';
        $pn->trade_type = isset($xml->trade_type) ? $xml->trade_type : '';
        $pn->bank_type = isset($xml->bank_type) ? $xml->bank_type : '';
        $pn->total_fee = isset($xml->total_fee) ? $xml->total_fee : '';
        $pn->settlement_total_fee = isset($xml->settlement_total_fee) ? $xml->settlement_total_fee : '';
        $pn->fee_type = isset($xml->fee_type) ? $xml->fee_type : '';
        $pn->cash_fee = isset($xml->cash_fee) ? $xml->cash_fee : '';
        $pn->cash_fee_type = isset($xml->cash_fee_type) ? $xml->cash_fee_type : '';
        $pn->coupon_fee = isset($xml->coupon_fee) ? $xml->coupon_fee : '';
        $pn->coupon_count = isset($xml->coupon_count) ? $xml->coupon_count : '';
        $pn->transaction_id = isset($xml->transaction_id) ? $xml->transaction_id : '';
        $pn->out_trade_no = isset($xml->out_trade_no) ? $xml->out_trade_no : '';
        $pn->attach = isset($xml->attach) ? $xml->attach : '';
        $pn->time_end = isset($xml->time_end) ? $xml->time_end : '';
        $pn->save();
    }

}
